import React, { Component } from 'react';
import { GLOBAL } from '../../../../config/global';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  PixelRatio,
  TextInput,
  FlatList,
  Alert,
  Animated
} from "react-native";
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import ToastUtil from '../../../../utils/toast';
import HTTP from '../../../../utils/http';
import { API, API_GENERATE } from '../../../../config/api';

const scale = GLOBAL.SCALE;
const purchaseImg = require('../../../../imgs/order/purchase.png'); // 采
const saleImg = require('../../../../imgs/order/sale.png'); // 销
const showImg = require('../../../../imgs/order/show.png'); // 打开
const closeImg = require('../../../../imgs/order/close.png'); // 关闭

export class OperatePlanProductDetailPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      title: '计划明细',
      headerTintColor: '#272727',
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#272727' />,
      headerStyle: [style.head.headerStyle, { backgroundColor: '#f5f5f5' }],
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      status: 'data',
      refreshIcon: false, // 下拉刷新图标
      listData: [],
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    let { suggestWeight, organId, organName, planDetailIds, categoryName } = props.navigation.state.params;
    this.organName = organName || '';
    this.suggestWeight = suggestWeight || '';
    this.categoryName = categoryName || '';
    this.pageParams = {
      searchKey: '',
      planDetailIds,
    }
  }

  async componentWillMount () {
    let { productItem } = this.props.navigation.state.params
    // 有productItem说明是变更计划列表进来的，只有一条，不需要请求
    if (productItem) {
      this.productItem = productItem;
    } else {
      this.initPage();
    }
  }

  async initPage () {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload
    })
    let res = await HTTP.POST(API_GENERATE(API.OPERATE_PLAN_PRODUCT_DETAIL), this.pageParams);
    if (res) {
      res = this.getBoxHeight(res);
      this.setState({
        status: res.length > 0 ? 'data' : 'empty',
        listData: res,
        refreshIcon: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  getBoxHeight = (res) => {
    if (res && res.length > 0) {
      res.forEach((item, index) => {
        if (index == 0) {
          item.showItem = true;
          item.boxHeight = new Animated.Value(255 * scale);
        } else {
          item.showItem = false;
          item.boxHeight = new Animated.Value(57 * scale);
        }
      })
    }
    return res
  }

  // 下拉刷新
  refresh = () => {
    this.reload = false;
    this.initPage();
  }

  reloadPage = () => {
    this.reload = true;
    this.initPage();
  }

  toggleItem = (index, currentHeight) => {
    let { listData } = this.state;
    listData[index].showItem = !listData[index].showItem;
    Animated.spring(currentHeight, {
      duration: 300,
      toValue: listData[index].showItem ? 255 * scale : 57 * scale,
    }).start()
    this.setState({ listData })
  }

  _renderFilterWrap = () => {
    return (
      <View style={styles.filterWrap}>
        <View style={{ flex: 1 }}>
          <Text numberOfLines={1}>{this.organName}</Text>
        </View>
        <TextInput
          ref="searchInput"
          style={styles.searchInput}
          underlineColorAndroid='transparent'
          placeholder={"请输入商品名称"}
          placeholderTextColor="rgba(39,39,39,.5)"
          maxLength={30}
          returnKeyType={'search'}
          defaultValue={this.pageParams.searchKey}
          onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
          onSubmitEditing={() => { this.reloadPage() }}
        />
      </View >
    )
  }

  _renderListItem = (data) => {
    let item = data.item;
    return (
      <View style={{ width: '100%' }}>
        <View style={[styles.listItem]}>
          <View style={styles.mainInfoWrap}>
            <Text numberOfLines={3} style={{ width: 100 * scale, fontWeight: 'bold', paddingTop: 2 * scale, paddingRight: 4 * scale }}>{item.goodsName || '--'}</Text>
            <View style={{ flex: 1, flexDirection: 'column', paddingRight: 12 * scale }}>
              <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 8 * scale }}>
                <Image style={{ marginRight: 5 * scale }} source={purchaseImg} />
                <Text style={{ fontSize: 13 * scale }} numberOfLines={2}>{item.supplierName || '--'}</Text>
              </View>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Image style={{ marginRight: 5 * scale }} source={saleImg} />
                <Text style={{ fontSize: 13 * scale }} numberOfLines={2}>{item.customerName || '--'}</Text>
              </View>
            </View>
          </View>

          <Animated.View style={[{ overflow: 'hidden', height: item.boxHeight }]}>
            <View style={styles.priceWrap}>
              <View style={{ flexDirection: 'row' }}>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>下达(计划)量(吨)</Text>
                  <Text numberOfLines={2}>{item.weight || '--'}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>需转采量(吨)</Text>
                  <Text numberOfLines={2}>{item.suggestWeight || '--'}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <View style={{ flexDirection: 'row' }}>
                    <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>价格(元/吨)</Text>
                    {
                      item.priceType == '1' ? (
                        <View style={[styles.priceType, { backgroundColor: 'rgba(20,140,251,.08)' }]}>
                          <Text style={{ color: '#148CFB', fontSize: 11 * scale }}>一口</Text>
                        </View>
                      ) : (
                          <View style={styles.priceType}>
                            <Text style={{ color: '#FA4516', fontSize: 11 * scale }}>暂定</Text>
                          </View>
                        )
                    }
                  </View>
                  <Text numberOfLines={2}>{item.price || '--'}</Text>
                </View>
              </View>
              <View style={{ flexDirection: 'row' }}>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>成本(元/吨)</Text>
                  <Text numberOfLines={2}>{item.capitalCost || '--'}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>运费(元/吨)</Text>
                  <Text numberOfLines={2}>{item.freight || '--'}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>落袋(元/吨)</Text>
                  <Text numberOfLines={2}>{item.netPrice || '--'}</Text>
                </View>
              </View>
            </View>

            <View style={{ flexDirection: 'column', justifyContent: 'space-around', height: 126 * scale, paddingTop: 12 * scale }}>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={[styles.commonText, { marginRight: 20 * scale }]}>是否长约</Text>
                <Text style={{ fontSize: 13 * scale }}>{item.isAgreement == '0' ? '否' : '是'}</Text>
              </View>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={[styles.commonText, { marginRight: 20 * scale }]}>交货方式</Text>
                <Text style={{ fontSize: 13 * scale }}>{item.deliveryWayName || '--'}</Text>
              </View>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={[styles.commonText, { marginRight: 20 * scale }]}>交货区域</Text>
                <Text numberOfLines={2} style={{ flex: 1, fontSize: 13 * scale }}>{item.deliveryPlace || '--'}</Text>
              </View>
              {
                item.formulaName ? (
                  <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <Text style={[styles.commonText, { marginRight: 20 * scale }]}>价格公式</Text>
                    <Text numberOfLines={3} style={{ flex: 1, fontSize: 13 * scale }}>{item.formulaName || '--'}</Text>
                  </View>
                ) : null
              }
            </View>
          </Animated.View>
        </View >
        <TouchableOpacity activeOpacity={1} style={styles.toggleImg} onPress={() => this.toggleItem(data.index, item.boxHeight)}>
          <Image style={{ marginTop: -1 * scale }} source={item.showItem ? closeImg : showImg} />
        </TouchableOpacity>
      </View>

    )
  }

  _renderProductItem = () => {
    let { goodsName, supplierName, customerName, isAgreement, deliveryWayName, deliveryPlace, formulaName, suggestWeight, newWeight, newIncrement, priceType, price, capitalCost, freight, netPrice } = this.productItem;
    let suggestNum = parseFloat(suggestWeight) || 0;
    let newNum = parseFloat(newWeight) || 0;
    let rangeWeight = newNum - suggestNum;
    return (
      <View style={[styles.listItem]}>
        <View style={styles.mainInfoWrap}>
          <Text numberOfLines={3} style={{ width: 100 * scale, fontWeight: 'bold', paddingTop: 2 * scale, paddingRight: 4 * scale }}>{goodsName || '--'}</Text>
          <View style={{ flex: 1, flexDirection: 'column', paddingRight: 12 * scale }}>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 8 * scale }}>
              <Image style={{ marginRight: 5 * scale }} source={purchaseImg} />
              <Text style={{ fontSize: 13 * scale }} numberOfLines={2}>{supplierName || '--'}</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Image style={{ marginRight: 5 * scale }} source={saleImg} />
              <Text style={{ fontSize: 13 * scale }} numberOfLines={2}>{customerName || '--'}</Text>
            </View>
          </View>
        </View>

        <View style={[{ overflow: 'hidden' }]}>
          <View style={styles.priceInfoWrap}>
            <View style={{ flexDirection: 'row' }}>
              <View style={{ flex: 1 }}>
                <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>下达(原计划)量(吨)</Text>
                <Text numberOfLines={2}>{suggestWeight || '--'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>下达(新计划)量(吨)</Text>
                <Text numberOfLines={2}>{newWeight || '--'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>幅度(吨)</Text>
                </View>
                <Text numberOfLines={2}>{rangeWeight || '--'}</Text>
              </View>
            </View>

            <View style={{ flexDirection: 'row', marginTop: 20 * scale, marginBottom: 20 * scale }}>
              <View style={{ flex: 1 }}>
                <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>需转采量(吨)</Text>
                <Text numberOfLines={2}>{newIncrement || '--'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>价格(元/吨)</Text>
                  {
                    priceType == '1' ? (
                      <View style={[styles.priceType, { backgroundColor: 'rgba(20,140,251,.08)' }]}>
                        <Text style={{ color: '#148CFB', fontSize: 11 * scale }}>一口</Text>
                      </View>
                    ) : (
                        <View style={styles.priceType}>
                          <Text style={{ color: '#FA4516', fontSize: 11 * scale }}>暂定</Text>
                        </View>
                      )
                  }
                </View>
                <Text numberOfLines={2}>{price || '--'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>成本(元/吨)</Text>
                </View>
                <Text numberOfLines={2}>{capitalCost || '--'}</Text>
              </View>
            </View>

            <View style={{ flexDirection: 'row' }}>
              <View style={{ flex: 1 }}>
                <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>运费(元/吨)</Text>
                <Text numberOfLines={2}>{freight || '--'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>落袋(元/吨)</Text>
                <Text numberOfLines={2}>{netPrice || '--'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <Text style={[styles.commonText, { marginBottom: 5 * scale }]}>是否长约</Text>
                <Text numberOfLines={2}>{isAgreement == '0' ? '否' : '是'}</Text>
              </View>
            </View>
          </View>

          <View style={{ flexDirection: 'column', justifyContent: 'space-around', paddingTop: 12 * scale }}>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 * scale }}>
              <Text style={[styles.commonText, { marginRight: 20 * scale }]}>交货方式</Text>
              <Text style={{ fontSize: 13 * scale }}>{deliveryWayName || '--'}</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 * scale }}>
              <Text style={[styles.commonText, { marginRight: 20 * scale }]}>交货区域</Text>
              <Text numberOfLines={2} style={{ flex: 1, fontSize: 13 * scale }}>{deliveryPlace || '--'}</Text>
            </View>
            {
              formulaName ? (
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <Text style={[styles.commonText, { marginRight: 20 * scale }]}>价格公式</Text>
                  <Text numberOfLines={3} style={{ flex: 1, fontSize: 13 * scale }}>{formulaName || '--'}</Text>
                </View>
              ) : null
            }
          </View>
        </View>


      </View >
    )
  }

  render () {
    let { status, listData, refreshIcon } = this.state;
    return (
      <View style={styles.container}>
        {this.productItem ? null : this._renderFilterWrap()}

        <View>
          <Text style={{ marginLeft: 12 * scale, marginBottom: 6 * scale }}>[ {this.categoryName} ]  当月计划:  {this.suggestWeight}吨</Text>
        </View>
        {
          status == 'data' ? (
            this.productItem ? (
              this._renderProductItem()
            ) : (
                <View style={styles.fastListWrap}>
                  <FlatList
                    data={listData}
                    renderItem={this._renderListItem}
                    refreshing={refreshIcon}
                    onRefresh={() => { this.refresh() }}
                  />
                </View>
              )
          ) : null
        }


        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.reloadPage} />) : null
        }
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#F5F5F5',
    flex: 1,
  },
  filterWrap: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: 13 * scale,
    marginTop: 4 * scale,
  },
  searchInput: {
    backgroundColor: '#fff',
    borderRadius: 2 * scale,
    height: 34 * scale,
    width: 270 * scale,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: '#EDEDED',
    textAlign: 'center',
    paddingVertical: 0,
  },
  fastListWrap: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    flex: 1,
    paddingBottom: 16 * scale,
  },
  listItem: {
    position: 'relative',
    backgroundColor: '#fff',
    borderRadius: 4 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    paddingBottom: 16 * scale,

  },
  mainInfoWrap: {
    flexDirection: 'row',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#EFEFEF',
    borderStyle: 'solid',
    height: 78 * scale,
    paddingTop: 15 * scale
  },
  priceWrap: {
    paddingTop: 12 * scale,
    paddingBottom: 12 * scale,
    height: 128 * scale,
    flexDirection: 'column',
    justifyContent: 'space-between',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#EFEFEF',
    borderStyle: 'solid',
  },
  priceInfoWrap: {
    paddingTop: 12 * scale,
    paddingBottom: 12 * scale,
    flexDirection: 'column',
    justifyContent: 'space-between',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#EFEFEF',
    borderStyle: 'solid',
  },
  commonText: {
    fontSize: 13 * scale,
    color: '#272727',
    opacity: .6
  },
  priceType: {
    height: 14 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(250,69,22,.08)',
    paddingLeft: 2 * scale,
    paddingRight: 2 * scale,
    borderRadius: 2 * scale,
  },
  toggleImg: {
    height: 30 * scale,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'flex-start',
    marginBottom: 10 * scale
  },
})